# -*- coding:utf-8 -*-
"""
if the music have the word 分手
"""
import re
import logging
import simplejson
from LyricStructure.pylyric.Lyric import Lyric

def get_privative_word(line):
    """
    : params line : the line for detection
    : return : list of info of the word and position
    """
    #logging.warning('to move to other common module')
    privative_word_list = [u"不"]

    winfo_list = []
    for w in privative_word_list:
        for m in re.finditer(w,line):
            winfo_list.append((w,m.start(),m.end()))
    return winfo_list

def predict_3_breakup(lrc_str,print_detail=False):
    """
    : params lrc_str : the string for the lyric file
    : return label and confidence
    """
    #print lrc_str
    l = Lyric()
    l.loadstr(lrc_str)
    lines = l.getlinelist()

    find_pattern = False
    for line in lines:
        line = line['content']
        if line.count(u'分手') != 0:
            #"""
            if print_detail:
                print line
            pv_winfo_list = get_privative_word(line)
            if print_detail:
                print len(pv_winfo_list)
            if print_detail:
                logging.info('pv count %d'%len(pv_winfo_list))
            if len(pv_winfo_list) != 0:
                continue
            #"""
            find_pattern = True
            break

    if find_pattern:
        return (-1,1)
    else:
        return (0,0)

def batch_run():
    from gdsettings import GD_DIR
    from commonprocess.read_ano import read_mid_p
    from pyweka.classifierresult import get_result_from_two_list,get_cm_from_two_list

    tr_mid_list = simplejson.load(open('%s/data/vote_split/train%d.json'%(GD_DIR,0)))
    te_mid_list = simplejson.load(open('%s/data/vote_split/test%d.json'%(GD_DIR,0)))
    mid_list = tr_mid_list+te_mid_list
    mid2p = read_mid_p()
    r_list = []
    p_list = []
    
    predict_mid_list = []
    for mid in mid_list:
        # try to predict
        lrc_str = open('/Users/wangxing/gd/lyrics/%s.lrc'%(mid)).read()
        l,c = predict_3_breakup(lrc_str.decode('gbk'))
        if c > 0:
            p_list.append( 1 if l > 0 else 0)
            r_list.append(1 if mid2p[mid] > 5 else 0)
            if p_list[-1] != r_list[-1]:
                print 'bad',mid,l,c
                print 
            predict_mid_list.append(mid)

    outf = open('./data/3_breakup.json','w')
    print>>outf,simplejson.dumps(predict_mid_list)
    outf.close()

    rdic = get_result_from_two_list(r_list,p_list)
    cm = get_cm_from_two_list(r_list,p_list)
    print rdic
    print cm

def run_one(mid):
    lrc_str = open('/Users/wangxing/gd/lyrics/%s.lrc'%(mid)).read()
    l,c = predict_3_breakup(lrc_str.decode('gbk'),True)
    print l,c

if __name__ == "__main__":
    batch_run()
    #run_one(240)
